import os
import re
import uuid
from typing import Annotated

from fastapi import APIRouter, Form, HTTPException, Depends, UploadFile, File
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

import models
from db import get_db
from datetime import datetime, timedelta
from jose import jwt
from auth import User, get_current_active_user
from auth import SECRET_KEY, pwd_context


router = APIRouter(prefix="/api/user", tags=["用户"])


@router.post("/login")
def login(phone: str = Form(), password: str = Form(), db: Session = Depends(get_db)):
    user = db.query(User).filter(User.phone == phone).first()
    if not user:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(password, user.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(minutes=60 * 24 * 15)
    token = jwt.encode({"user_id": user.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"token": token}



@router.post("/register")
async def register_with_avatar(name: str = Form(...),
                               password: str = Form(...),
                               phone: str = Form(...),
                               password_confirm: str = Form(...),
                               avatar: UploadFile = File(None),
                               db: Session = Depends(get_db)):
    phone = re.sub(r'\D', '', phone)
    if not re.match(r'^1[3-9]\d{9}$', phone):
        raise HTTPException(status_code=400, detail="手机号格式错误")
    if password!= password_confirm:
        raise HTTPException(status_code=400, detail="两次密码不一致")
    db_root = db.query(User).filter(User.phone == phone).first()
    if db_root:
        db.close()
        raise HTTPException(status_code=400, detail="用户已存在")
    hashed_password = pwd_context.hash(password)
    if len(password) < 8:
        raise HTTPException(status_code=400, detail="密码长度至少为8位")
    unique_id = uuid.uuid4()
    if avatar:
        file_extension = os.path.splitext(avatar.filename)[1]
        unique_filename = f"{unique_id}{file_extension}"
        file_path = os.path.join(storage_path, unique_filename)
        with open(file_path, "wb") as buffer:
            buffer.write(await avatar.read())
        avatar_path = f"storage/{unique_filename}"
    else:
        avatar_path = None
    new_user = User(name=name, phone=phone, password=hashed_password, avatar=avatar_path)
    db.add(new_user)
    db.commit()
    db.close()
    return {"message": "注册成功"}




@router.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(User).filter(User.phone == form_data.username).first()
    if not user:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(form_data.password, user.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(hours=24)
    token = jwt.encode({"user_id": user.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"access_token": token, "toke_type": "bearer", "code": 200}








storage_path = os.path.join(os.getcwd(), 'storage')
if not os.path.exists(storage_path):
    os.makedirs(storage_path)
@router.post("/upload")
async def upload_image(current_user: Annotated[models.User, Depends(get_current_active_user)],image: UploadFile = File(...)):
    unique_id = uuid.uuid4()
    file_extension = os.path.splitext(image.filename)[1]
    unique_filename = f"{unique_id}{file_extension}"
    file_path = os.path.join(storage_path, unique_filename)
    with open(file_path, "wb") as buffer:
        buffer.write(await image.read())
    if file_extension not in [".jpg", ".jpeg", ".png"]:
        raise HTTPException(status_code=400, detail="不支持的文件类型")
    return {"path": f"storage/{unique_filename}", "url": f"http://127.0.0.1:8000/storage/{unique_filename}"}















